import { base64_encode, base64_decode } from 'vender/base64.js';

const formatTime = (date=new Date()) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 切割数组
const split_array = (arr, len) => {
  let arr_length = arr.length;
  let newArr = [];
  for (let i = 0; i < arr_length; i += len) {
    newArr.push(arr.slice(i, i + len));
  }
  return newArr;
}

const getSystemInfo = () => {
  try {
    const res = wx.getSystemInfoSync()
    return res
  } catch (e) {
    // Do something when catch error
  }
}

const filterImg = (cont) => {
  return cont.replace(/\<img/gi, '<img class="rich-img" ')
}

const tost = (text, isState = false) => {
  wx.showToast({
    title: text,
    icon: isState ? "success" : "none"
  })
}

const verifyPhone = (phone) => { // 判断电话号码
  const myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
  if (phone.length < 11) {
    tost("手机号码最短需要 11 个位")
    return false
  } else {
    if (!myreg.test(phone)) {
      tost("手机号格式有误")
      return false
    }
  }
  return true
}

let returnFloat = (num) => {
  let result = parseFloat(num);
  if (isNaN(result)) {
    console.log('传递参数错误，请检查！');
    return false;
  }
  result = Math.round(num * 100) / 100;
  let s_x = result.toString();
  let pos_decimal = s_x.indexOf('.');
  if (pos_decimal < 0) {
    pos_decimal = s_x.length;
    s_x += '.';
  }
  while (s_x.length <= pos_decimal + 2) {
    s_x += '0';
  }
  return Number(s_x);
}

let getNowFormatDate = () => {
  let date = new Date();
  let seperator1 = "-";
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  let currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}

let getCountDays = () => {
  let curDate = new Date();
  /* 获取当前月份 */
  let curMonth = curDate.getMonth();
  /*  生成实际的月份: 由于curMonth会比实际月份小1, 故需加1 */
  curDate.setMonth(curMonth + 1);
  /* 将日期设置为0, 这里为什么要这样设置, 我不知道原因, 这是从网上学来的 */
  curDate.setDate(0);
  /* 返回当月的天数 */
  return curDate.getDate();
}

const toChinesNum = (num) => {
  let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']; //changeNum[0] = "零"
  let unit = ["", "十", "百", "千", "万"];
  num = parseInt(num);
  let getWan = (temp) => {
      let strArr = temp.toString().split("").reverse();
      let newNum = "";
      for (var i = 0; i < strArr.length; i++) {
        newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]) )) + newNum;
      }
      return newNum;
  }
  let overWan = Math.floor(num / 10000);
  let noWan = num % 10000;
  if (noWan.toString().length < 4) noWan = "0" + noWan;
  return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
}




const getNowDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth()
  const day = date.getDate()
  const weekArr = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
  return {
    year: year,
    month: weekArr[month],
    day: formatNumber(day)
  }
}


const cunTimetype = () => {
  let date = getNowDate(new Date())
  let NewData = date.day
  let dateInfo = {
    time: NewData,
    type: 0
  }
  let dateTime = wx.getStorageSync('date');
  if (dateTime) {
    if (NewData != dateTime.time) {
      wx.setStorageSync('date', dateInfo)
    }
  } else {
    wx.setStorageSync('date', dateInfo)
  }
}

const signSucceed = (day) => {
  let dateInfo = { time: day, type: 1 }
  wx.setStorageSync('date', dateInfo)
  let score = wx.getStorageSync('score') || 0
  wx.setStorageSync('score', score + 20)
  signListTap()
}



const signListTap = (text) => {
  let data = {
    time: formatTime(new Date()),
    type: 1
  }
  let signDynamic = wx.getStorageSync('signDynamic') || []
  signDynamic.push(data)
  wx.setStorageSync('signDynamic', signDynamic)
}

const base64Encode = (str)=> {
  return base64_encode(str)
};

const base64Decode = (str)=> {
  return base64_decode(str)
};


/**
 * 获取两点距离
 */
//将用角度表示的角转换为近似相等的用弧度表示的角 java Math.toRadians  
function rad(d) {
  return d * Math.PI / 180.0;
}

/** 
 * 谷歌地图计算两个坐标点的距离 
 * @param lng1  经度1 
 * @param lat1  纬度1 
 * @param lng2  经度2 
 * @param lat2  纬度2 
 * @return 距离（千米） 
 */
function getDistance(lng1, lat1, lng2, lat2) {
  var EARTH_RADIUS = 6378.137; //地球半径  
  var radLat1 = rad(lat1);
  var radLat2 = rad(lat2);
  var a = radLat1 - radLat2;
  var b = rad(lng1) - rad(lng2);
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
    + Math.cos(radLat1) * Math.cos(radLat2)
    * Math.pow(Math.sin(b / 2), 2)));
  s = s * EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000;
  return s;
}


module.exports = {
  formatTime,
  splitArray: split_array,
  getSystemInfo,
  filterImg,
  verifyPhone,
  tost,
  returnFloat,
  getNowFormatDate,
  getCountDays,
  toChinesNum,
  getNowDate,
  cunTimetype,
  signSucceed,
  signListTap,
  base64Encode,
  base64Decode,
  getDistance
}
